const config = require("../config/webpack.prod.config");
const paths = require("../config/paths");
const FileSizeReporter = require("../utils/FileSizeReporter.js");

const webpack = require("webpack");
const chalk = require("chalk");
const fs = require("fs-extra");
const execSync = require("child_process").execSync;

const measureFileSizesBeforeBuild = FileSizeReporter.measureFileSizesBeforeBuild;
const printFileSizesAfterBuild = FileSizeReporter.printFileSizesAfterBuild;
// These sizes are pretty large. We'll warn for bundles exceeding them.
const WARN_AFTER_BUNDLE_GZIP_SIZE = 512 * 1024;
const WARN_AFTER_CHUNK_GZIP_SIZE = 1024 * 1024;

measureFileSizesBeforeBuild(paths.appBuild)
  .then(previousFileSizes => {
    console.log("building for production...");
    // Remove all content but keep the directory so that
    // if you're in it, you don't end up in Trash
    fs.emptyDirSync(paths.appBuild);
    // Merge with the public folder
    copyPublicFolder();
    // Start the webpack build
    return build(previousFileSizes);
  })
  .then(
    ({ stats, previousFileSizes }) => {
      console.log(chalk.green("Compiled successfully.\n"));
      console.log("File sizes after gzip:\n");
      fs.writeFile("heartbeat.js", "console.log('heartbeat')", err => {
        if (err) {
          console.error(err);
        } else {
          execSync("mv heartbeat.js " + paths.appBuild + "/static/");
        }
      });
      printFileSizesAfterBuild(
        stats,
        previousFileSizes,
        paths.appBuild,
        WARN_AFTER_BUNDLE_GZIP_SIZE,
        WARN_AFTER_CHUNK_GZIP_SIZE
      );
    },
    err => {
      console.log(chalk.red("Failed to compile.\n"));
      process.exit(1);
    }
  )
  .catch(err => {
    if (err && err.message) {
      console.log(err.message);
    }
    process.exit(1);
  });

// webpack(config, function (err, stats) {

//     if (err) {
//         throw err
//     }
//     console.log(chalk.green('Compiled successfully.\n'));
//     process.stdout.write(stats.toString({
//         colors: true,
//         modules: false,
//         children: false,
//         chunks: false,
//         chunkModules: false
//       }) + '\n')
// })

function build(previousFileSizes) {
  let compiler = webpack(config);
  return new Promise((resolve, reject) => {
    compiler.run((err, stats) => {
      if (err) {
        return reject(err);
      }
      const resolveArgs = {
        stats,
        previousFileSizes
      };
      return resolve(resolveArgs);
    });
  });
}

function copyPublicFolder() {
  fs.copySync(paths.appPublic, paths.appBuild, {
    dereference: true,
    filter: file => file !== paths.appHtml
  });

  if (fs.pathExistsSync(paths.appAssets + "/skill_old")) {
    // 对于老子技能的项目页面打包
    fs.copySync(paths.appAssets + "/skill_old", paths.appPath + "/build/console/skill_old/", {
      dereference: true,
      filter: file => file !== paths.appHtml
    });
  }
}
